﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Configuration;

namespace Otgruzka.Helpers
{
    public static class GraphicHelper
    {

        public static Image ScaleByPercent(Image imgPhoto, Double? width = null)
        {
            if (width == null)
            {
                if (ConfigurationManager.AppSettings["SmallImageWidth"] == null)
                    width = 0.0;
                else
                {
                    string widthStr = ConfigurationManager.AppSettings["SmallImageWidth"].ToString().Replace('.', ',');
                    width = Double.Parse(widthStr);
                }
            }

            Int32 sourceWidth = imgPhoto.Width;
            Int32 sourceHeight = imgPhoto.Height;
            Int32 sourceX = 0;
            Int32 sourceY = 0;

            Double nPercent = width.Value/sourceWidth;
            Int32 destX = 0;
            Int32 destY = 0;
            Int32 destWidth = (Int32)(sourceWidth * nPercent);
            Int32 destHeight = (Int32)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
    }
}